package com.sloan.community.util;

import org.codehaus.jettison.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: yaosj
 * @CreateTime: 2024-12-14
 */
public class IpUtils {

    public static void main(String[] args) {
        try {
            // 使用 ip-api API 获取公网IP
            String apiUrl = "http://ip-api.com/json";  // 获取 JSON 格式的响应
            HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
            connection.setRequestMethod("GET");

            // 读取 API 返回的 JSON 数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 数据，获取公网 IP
            String jsonResponse = response.toString();
            System.out.println("Response: " + jsonResponse);

            // 从返回的 JSON 中提取 IP 信息
            // 解析JSON数据，获取 IP 地址
            int start = jsonResponse.indexOf("\"query\":\"") + 9;
            int end = jsonResponse.indexOf("\"", start);
            String publicIP = jsonResponse.substring(start, end);

            System.out.println("Your public IP is: " + publicIP);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main02(String[] args) {
        try {
            // 获取外部API地址，使用ip-api（免费版）
            String apiUrl = "http://ip-api.com/json";  // 这里不带IP地址，默认获取当前IP
            HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 获取API返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON响应
            JSONObject jsonResponse = new JSONObject(response.toString());

            String country = jsonResponse.getString("country");
            String region = jsonResponse.getString("regionName");
            String city = jsonResponse.getString("city");

            // 判断并输出地址
            if ("China".equals(country)) {
                // 如果是中国，则输出省份
                System.out.println("您所在的位置是：中国 " + region);
            } else {
                // 如果是国外，则输出国家
                System.out.println("您所在的位置是：" + country);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
